// pages/addressList/addressList.js
var api = require('../../api/api');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address_list: [],
    default_state: false,
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
  },
  

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddress();
  },
  switch1Change(e){
    let index = e.currentTarget.dataset.index;
    let id = this.data.address_list[index].id;
    api.post('/user/saveDefaultAddress/'+id).then(res=>{
      let lists = this.data.address_list;
      lists.map(item=>{
        item.is_default = false;
      })
      lists[index].is_default = !lists[index].is_default
      wx.setStorageSync('address', lists[index])
      this.setData({
        address_list:lists
      })
    })
  },
  selectAddress(e){

    let index = e.currentTarget.dataset.index;
    let lists = this.data.address_list;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      address:lists[index]
    })
    wx.navigateBack({
      delta: 1,
    })
  },
  edit(e){
    let index = e.currentTarget.dataset.index;
    let lists = this.data.address_list;
    let id = this.data.address_list[index].id;
    wx.setStorageSync('editAddress', lists[index]);
    wx.navigateTo({
      url: '/pages/address/address?edit=1&id='+id,
    })
  },
  del(e){
    let index = e.currentTarget.dataset.index;
    let id = this.data.address_list[index].id;
    api.post('/user/delAddress/'+id).then(res=>{
      let lists = this.data.address_list;
      lists.splice(index,1);
      this.setData({
        address_list:lists
      })
    })
  },
  getAddress(){
    api.get('/user/address').then(res=>{
      this.setData({
        address_list:res.items
      })
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: '../address/address'
    });
  }
})